package com.example.springbott.typehandler;

import com.example.springbott.util.StringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringInterArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(i,value);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, String s) throws SQLException {
        return transfer(resultSet.getString(s));
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int i) throws SQLException {
       return transfer(resultSet.getString(i));
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        return transfer(callableStatement.getString(i));
    }
    @SneakyThrows
    private Integer[] transfer(String s){
        if (!StringUtil.isEmpty(s)){
            Integer[] integers = objectMapper.readValue(s, Integer[].class);
            return integers;
        }
        return new Integer[0];


    }
}
